<template>
  <div class="main">
    <p class="success" v-if="status == 1">{{$t('mall.payment_successful')}}!</p>
    <p class="cancel" v-if="status == 2">{{$t('mall.payment_canceled')}}!</p>
    <el-button type="primary" class="bock" @click="returnBeforePage">{{$t('mall.back')}}{{ seconds }}</el-button>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { confirmPayOrder, cancelUnPayOrder } from '@/server/api/biz.js';
const route = useRoute();
const router = useRouter();
let status = ref(route.query.payType);
const orderData = ref({});
const seconds = ref(5);

onMounted(() => {
  setPayStatus();
});

/**
 * 设置支付状态
 */
const setPayStatus = () => {
  let data = JSON.parse(localStorage.getItem('orderInfo')) || {};
  orderData.value = data;
  if (status.value == 1) {
    confirmPay();
  } else {
    cancelPay();
  }

  const countdown = (secondsNum) => {
    if (secondsNum < 1) {
      // 倒计时结束，执行你的代码
      router.push({
        path: '/order',
        query: {
          type: 0,
          tabs: data.tabs,
        },
      });
    } else {
      // 递归调用，每秒减少一次
      setTimeout(function () {
        seconds.value = secondsNum - 1;
        countdown(seconds.value);
      }, 1000);
    }
  };

  // 调用函数开始倒计时
  countdown(seconds.value);
};

const returnBeforePage = () => {
  let data = JSON.parse(localStorage.getItem('orderInfo')) || {};
  router.push({
    path: '/order',
    query: {
      type: 0,
      tabs: data.tabs,
    },
  });
};

/**
 * 确认支付
 */
const confirmPay = () => {
  const obj = {
    payId: orderData.value.id,
    payOrderId: orderData.value.payOrderId,
    pcbaOrderId: orderData.value.pcbaOrderId,
  };
  confirmPayOrder(obj).then((res) => {
    if (res.code === 200) {
      status.value = 1;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 取消支付
 */
const cancelPay = () => {
  const obj = {
    payId: orderData.value.id,
    payOrderId: orderData.value.payOrderId,
  };
  cancelUnPayOrder(obj).then((res) => {
    if (res.code === 200) {
      status.value = 2;
      // router.push({
      //   path: '/order',
      //   query: {
      //     type: 0,
      //   },
      // });
    } else {
      ElMessage.error(res.msg);
    }
  });
};
</script>
<style scoped>
.main {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.success {
  margin-top: 100px;
  color: #67c23a;
  font-size: 20px;
  text-align: center;
  font-weight: bold;
  margin-bottom: 50px;
}

.cancel {
  margin-top: 100px;
  color: #f56c6c;
  font-size: 20px;
  text-align: center;
  font-weight: bold;
  margin-bottom: 50px;
}
</style>
